from collections import OrderedDict

from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.contents.models import ContentCategory
from apps.goods.models import GoodsChannel


class IndexView(View):
    """首页广告"""

    def get(self, request):
        """提供首页广告界面"""
        categories = OrderedDict()
        channels = GoodsChannel.objects.order_by('group_id','sequence')
        for channel in channels:
            group_id = channel.group_id
            if group_id not in categories:
                categories[group_id] = {'channels':[],'sub_cats':[]}
            cat1 = channel.category
            categories[group_id]['channels'].append({'id':cat1.id,
                                                     'name':cat1.name,
                                                     'url':channel.url})
            for cat2 in cat1.subs.all():

                cat2.sub_cats = []
                for cat3 in cat2.subs.all():
                    cat2.sub_cats.append(cat3)
                categories[group_id]['sub_cats'].append(cat2)

        #  广告数据
        contents = {}
        content_categeories = ContentCategory.objects.all()
        for cat in content_categeories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        print(contents)
        context = {
                'categories': categories,
                'contents':contents
            }

        return render(request, 'index.html', context)


